package com.yao.club.service.impl;

import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.GoodsComment;
import com.yao.club.entity.dto.GoodsCommentLikeRecord;
import com.yao.club.entity.dto.SysImg;
import com.yao.club.entity.request.CommentRequest;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.entity.vo.GoodsCommentVO;
import com.yao.club.mapper.UserMapper;
import com.yao.club.reposittory.GoodsCommentLikeRecordRepository;
import com.yao.club.reposittory.GoodsCommentRepository;
import com.yao.club.reposittory.SysImageRepository;
import com.yao.club.service.GoodsCommentService;
import com.yao.club.utils.ResponseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsCommentServiceImpl implements GoodsCommentService {

    @Autowired
    private GoodsCommentRepository commentRepository;

    @Autowired
    private GoodsCommentLikeRecordRepository likeRecordRepository;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysImageRepository sysImageRepository;

    @Override
    public ResponseEntity<ResultEntity<GoodsCommentVO>> pageComments(Long goodsId, Integer pageNum, Integer pageSize, String username) {
        try {
            Pageable pageable = PageRequest.of(pageNum - 1, pageSize,Sort.by(Sort.Direction.DESC, "createTime"));
            // 获取一级评论
            Page<GoodsComment> page = commentRepository.findGoodsCommentByGoodsIdAndLevel(goodsId, 1,pageable);

            List<GoodsCommentVO> commentVOs = page.getContent().stream()
                .map(comment -> convertToVO(comment, username))
                .collect(Collectors.toList());

            // 获取每个评论的回复
            for (GoodsCommentVO commentVO : commentVOs) {
                List<GoodsComment> replies = commentRepository.findByParentId(commentVO.getGoodsCommentId());
                commentVO.setReplies(replies.stream()
                    .map(reply -> convertToVO(reply, username))
                    .collect(Collectors.toList()));
            }

            ResultEntity<GoodsCommentVO> result = new ResultEntity<>();
            result.setRecords(commentVOs);
            result.setTotal((int) page.getTotalElements());
            result.setSize(pageSize);
            result.setCurrent(pageNum);
            result.setPages(page.getTotalPages());

            return ResponseUtils.success(result);
        } catch (Exception e) {
            return ResponseUtils.failed("获取评论失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseEntity<Boolean> addComment(CommentRequest request, String username) {
        try {
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            GoodsComment comment = new GoodsComment();
            comment.setGoodsId(request.getGoodsId());
            comment.setContent(request.getContent());
            comment.setCreateBy(user.getMember_id()+"");
            comment.setCreateTime(Instant.now());
            commentRepository.save(comment);
            return ResponseUtils.success(true);
        } catch (Exception e) {
            return ResponseUtils.failed("发布评论失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseEntity<Boolean> replyComment(CommentRequest request, String username) {
        try {
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            // 验证父评论是否存在
            if (!commentRepository.existsById(request.getParentId())) {
                return ResponseUtils.failed("回复的评论不存在");
            }

            GoodsComment reply = new GoodsComment();
            reply.setGoodsId(request.getGoodsId());
            reply.setContent(request.getContent());
            reply.setCreateBy(user.getMember_id()+"");
            reply.setParentId(request.getParentId());
            reply.setCreateTime(Instant.now());

            commentRepository.save(reply);
            return ResponseUtils.success(true);
        } catch (Exception e) {
            return ResponseUtils.failed("回复评论失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseEntity<Boolean> toggleCommentLike(Long commentId, String username) {
        try {
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            List<GoodsCommentLikeRecord> existingLike = likeRecordRepository.findGoodsCommentLikeRecordByGoodsCommentIdAndUserId(commentId, user.getMember_id());


            if (existingLike != null) {
                // 取消点赞
                likeRecordRepository.delete(existingLike.get(0));
                commentRepository.decrementLikeCount(commentId);
                return ResponseUtils.success(false);
            } else {
                // 添加点赞
                GoodsCommentLikeRecord like = new GoodsCommentLikeRecord();
                like.setGoodsCommentId(commentId);
                like.setUserId(user.getMember_id());
                like.setCreateTime(Instant.now());
                likeRecordRepository.save(like);
                commentRepository.incrementLikeCount(commentId);
                return ResponseUtils.success(true);
            }
        } catch (Exception e) {
            return ResponseUtils.failed("操作失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ResponseEntity<Boolean> deleteComment(Long commentId, String username) {
        try {
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }

            GoodsComment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("评论不存在"));

            // 验证是否是评论作者
            if (!comment.getCreateBy().equals(user.getMember_id())) {
                return ResponseUtils.failed("无权删除此评论");
            }

            // 删除评论及其回复
            commentRepository.deleteByIdOrParentId(commentId);
            // 删除相关的点赞记录
            likeRecordRepository.deleteGoodsCommentLikeRecordByGoodsCommentId(commentId);

            return ResponseUtils.success(true);
        } catch (Exception e) {
            return ResponseUtils.failed("删除评论失败：" + e.getMessage());
        }
    }

    private GoodsCommentVO convertToVO(GoodsComment comment, String username) {
        GoodsCommentVO vo = new GoodsCommentVO();
        BeanUtils.copyProperties(comment, vo);

        // 设置用户信息
        UserEntity user = userMapper.getUserByMemberId(comment.getCreateBy());
        if (user != null) {
            vo.setCreateBy(user.getNickname());
            SysImg sysImg = sysImageRepository.selectById(user.getAvatar_id() + "");
            vo.setHeadImg(sysImg);
        }

        // 设置点赞状态
        if (username != null) {
            UserEntity currentUser = userMapper.select(username);
            if (currentUser != null) {
                List<GoodsCommentLikeRecord> likeRecord = likeRecordRepository
                    .findGoodsCommentLikeRecordByGoodsCommentIdAndUserId(comment.getGoodsCommentId(), currentUser.getMember_id());
                vo.setIsLike(likeRecord != null && likeRecord.size() > 0);
            }
        }

        return vo;
    }
} 